package com.yeyks.rabbitmq.queue;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fuchangshuai
 * @date 2019/4/17
 *
 * 关键字理解：
 * RoutingKey：指定当前消息被谁接受（发送消息的时候会传exchange和RoutingKey）
 *
 * Exchange：是接受生产者消息并将消息路由到消息队列的关键组件，生产者想要发送消息，
 *          首先必须要声明一个Exchange和该Exchange对应的Binding
 *
 * BindingKey：指定当前Exchange下，什么样的RoutingKey会被下派到当前绑定的Queue中
 */
@Configuration
public class DelayRabbitMqQueue {

    /**
     * 可以理解为：延迟时间过后延迟队列死亡，使用该队列(A)发送消息
     */
    public static final String ORDER_QUEUE = "order.queue";
    /**
     * A队列接收消息的对象
     */
    private static final String ORDER_EXCHANGE = "order.exchange";
    /**
     * A队列绑定的binging.key
     */
    private static final String ORDER_BINDING_KEY = "order.binding.Key";
    /**
     * 延迟队列
     */
    private static final String ORDER_DELAY_QUEUE = "order.delay.queue";
    /**
     * 延迟队列接收消息的对象
     */
    public static final String ORDER_DELAY_EXCHANGE = "order.delay.exchange";
    /**
     * 延迟队列绑定的binging.key
     */
    public static final String ORDER_DELAY_BINDING_KEY = "order.delay.binding";

    /**
     * 延迟队列配置
     **/
    @Bean
    public Queue delayOrderQueue() {
        Map<String, Object> params = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信(延迟时间已过)转发到的DLX名称，
        params.put("x-dead-letter-exchange", ORDER_EXCHANGE);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", ORDER_BINDING_KEY);
        return new Queue(ORDER_DELAY_QUEUE, true, false, false, params);
    }

    /**
     * 延迟队列 Exchange
     *
     * @return DirectExchange
     */
    @Bean
    public DirectExchange orderDelayExchange() {
        return new DirectExchange(ORDER_DELAY_EXCHANGE);
    }

    /**
     * 将延迟队列和exchange绑定
     *
     * @return
     */
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(delayOrderQueue()).to(orderDelayExchange()).with(ORDER_DELAY_BINDING_KEY);
    }

    /**
     * 将要执行死信(延迟时间已过)的队列
     *
     * @return
     */
    @Bean
    public Queue orderQueue() {
        return new Queue(ORDER_QUEUE, true);
    }

    /**
     * 执行死信的队列的exchange
     *
     * @return
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 将执行死信的队列与exchange绑定
     *
     * @return
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(ORDER_BINDING_KEY);
    }
}
